<template>
	<view class="footer1">
		<view class="btn-container">
			<button @click="getDeck()">摸牌</button>
			<button @click="win()" :class="{ 'can-win': isWin, 'not-win': !isWin }">
			    {{ isWin ? '胡牌' : '未胡' }}
			</button>
			<button @click="checkIfWin()">提示</button>
			<button @click="handleDeckGang()" :class="{ 'can-gang': canGang }">杠</button>
		</view>
		<view class="cards">
		    <view class="card" v-for="(item,index) in handPoolArray" :key="index"
		        :class="cardClass(index)"
		        @click="handleDeckClick(index, item)">
				<image :src="'/static/majiang/' + item + '.png'"></image>
		    </view>
		</view>
	</view>
</template>

<script>
	export default {
		props: ['deck','outPool'],
		data() {
			return {
				handPool: {},
				canOut: true,
				canGet: false,
				isWin: false,
				newIndex: -1,
				newCard: -1,
				clickedIndex: -1,
				opeList: [],
				gangArray: [],
				canGang: false,
				counts: {},
				willWinArray: [],
				winningArray: [],
				aiTile: -1,
			}
		},
		watch: {
			'deck.total'(newVal) {
				if (newVal === 0) {
					uni.showModal({
						title: '游戏结束',
						content: '请点击开始下一局',
						showCancel: false,
						success: function(res) {
							// 用户点击了确定按钮，可以执行一些操作
						}
					});
				}
			},
			'aiTile'(newTile) {
			    console.log(newTile)
			}
		},
		computed: {
		    cardClass() {
				return (index) => {
					return {
						'new-card': index === this.newIndex,
						'is-clicked': index === this.clickedIndex,
						'will-win': this.willWinArray.includes(this.handPoolArray[index]),
						'ope-choosed': this.canGang && this.handPool[this.handPoolArray[index]] === 4,
					}
				}
			},
			handPoolArray() {
				const arr = [];
				for (const key in this.handPool) {
					if (this.handPool.hasOwnProperty(key)) {
						const count = this.handPool[key];
						for (let i = 0; i < count; i++) {
							arr.push(Number(key));
						}
					}
				}
				return arr;
			},
		},
		created() {
			this.getHandPool();
			this.deckPoolCountInit();
			this.aiGetHandPool();
		},
		methods: {
			getHandPool() {
				const tem = this.deck.deckPool.splice(0,14);
				for (let i = 0; i < tem.length; i++) {
					this.handPool[tem[i]] = (this.handPool[tem[i]] || 0) + 1;
					this.reduceDeck(tem[i])
				}
			},
			deckPoolCountInit() {
				this.deck.deckPoolCounts = {}
				const deckPool = [...this.deck.deckPool]
				for (let i = 0; i < deckPool.length; i++) {
					this.deck.deckPoolCounts[deckPool[i]] = (this.deck.deckPoolCounts[deckPool[i]] || 0) + 1;
				}
			},
			aiGetHandPool() {
				const tem = this.deck.deckPool.splice(0,42);
				for (let i = 0; i < tem.length; i++) {
					this.reduceDeckThird()
				}
			},
			checkIfWin() {
				this.willWinArray = []
				let keys = Object.keys(this.handPool);
				for (let i = 0; i < keys.length; i++) {
					const key = Number(keys[i]);
					if (this.showWinningTips(key).length > 0) {
						this.willWinArray.push(key)
					}
				}
			},
			handleDeckGang() {
				this.canGang = !this.canGang
			},
			
			handleDeckClick(index, item) {
				if (!this.canGang) {
					if (this.clickedIndex === index) {
						// 如果该牌已经被点击，执行出牌操作
						this.outDeck(item);
						this.clickedIndex = -1;  // 恢复原始状态
					} else {
						this.clickedIndex = index;
						this.winningArray = this.showWinningTips(item);
						uni.$emit('winning', this.winningArray);
					}
				} else {
					this.clickedIndex = -1;  // 恢复原始状态
					if (this.handPool[Number(item)] === 4) {
						this.opeList[Number(item)] = 4
						this.handPool[Number(item)] = 0
						
						this.canGet = true;
						this.canGang = false
						
						uni.$emit('ope', {...this.opeList})
						this.getDeckByCondition(true)
					}
				}
			},
			outDeck(key) {
				if (!this.canOut) {
					console.log("请先摸牌")
					return;
				}
				
				this.handPool[key]--;
				
				this.outPool.push(key);
				
				// setTimeout(() => {
				// 	this.aiOut();
				// },500);
				
				// setTimeout(() => {
				// 	this.aiOut();
				// },1000);
				
				// setTimeout(() => {
				// 	this.aiOut();
				// },1500);
				
				setTimeout(() => {
					this.canGet = true;
				},100);
				
				this.whenOutClear();
			},
			
			whenOutClear() {
				this.canOut = false;
				this.newIndex = -1;
				this.willWinArray = []
			},
			aiOut() {
				const nu = this.deck.deckPool.splice(0,1);
				this.outPool.push(nu);
				this.reduceDeck(nu);
			},
			getDeck() {
				this.getDeckByCondition(false)
			},
			getDeckByCondition(isGang) {
				this.winningArray = []
				
				if (!this.canGet) {
					console.log("请出牌")
					return
				}
				
				if (this.deck.total === 0) {
					console.log("结束牌局");
					return;
				}
				
				let nu = -1;
				if (!isGang) {
					nu = this.deck.deckPool.splice(0,1)[0];
				} else {
					nu = this.deck.deckPool.pop()
				}
				
				this.newIndex = this.handPoolArray.findIndex((num) => num >= nu) !== -1 ? this.handPoolArray.findIndex((num) => num >= nu) : this.handPoolArray.length;
				
				this.handPool[nu] = (this.handPool[nu] || 0) + 1;
				this.newCard = nu;
				
				this.isWin = this.checkWin(this.handPool)
				
				this.reduceDeck(nu);
				
				this.canGet = false;
				this.canOut = true;
			},
			reduceDeckThird() {
				this.deck.total--;
			},
			reduceDeck(nu) {
				if (nu >= 1 && nu <= 9) {
					this.deck.tongCount--;
				} else if (nu >= 11 && nu <= 19) {
					this.deck.wanCount--;
				} else {
					this.deck.tiaoCount--;
				}
				this.deck.deckPoolCounts[nu]--;
				this.deck.total--;
			},
			win() {
				if(this.win) {
					uni.showModal({
						title: '游戏结束',
						content: '请点击开始下一局',
						showCancel: false,
						success: function(res) {
							// 用户点击了确定按钮，可以执行一些操作
						}
					});
				}
			},
			showWinningTips(key) {
				let newPool = {...this.handPool};
				newPool[key]--;
				return this.checkWinningTips(newPool);
			},
			checkWinningTips(pool) {
				let winningArray = []
				let keys = Object.keys(this.deck.deckPoolCounts)
				for (let i = 0; i < keys.length; i++) {
					const key = Number(keys[i]);
					let newPool = {...pool}
					newPool[key] = (newPool[key] || 0) + 1;
					const isWin = this.checkWin(newPool)
					if (isWin) {
						winningArray.push(key)
					}
				}
				return winningArray
			},
			checkWin(counts) {
			  // if (handPool.length % 3 !== 2) {
			  //   return false;
			  // }
			  
			  // headCounts: 每张数量大于2的牌的牌数对
			  let headCounts = {}
			  let countsKeys = Object.keys(counts);
			  for (let i = 0; i < countsKeys.length; i++) {
			    const key = countsKeys[i];
			    const count = counts[key];
			    if (count >= 2) {
			      headCounts[key] = count;
			    }
			  }
			  
			  let headCountsKeys = Object.keys(headCounts)
			  if (headCountsKeys.length === 0) {
			    return false;
			  }
			  
			  for (let i = 0; i < headCountsKeys.length; i++) {
			    const key = headCountsKeys[i];
				const newCounts = {...counts};
				newCounts[key] -= 2
				if (this.check(newCounts)) {
					return true
				}
			  }
			  return false;
			},
			check(counts) {
				let keys = Object.keys(counts);
				let i = 0;
				while (i < keys.length - 2) {
					if (counts[keys[i]] === 0) {
						i++;
						continue;
					}
					if (counts[keys[i]] === 3) {
						counts[keys[i]] -= 3;
						continue;
					}
					if (counts[parseInt(keys[i]) + 1] === 0 || counts[parseInt(keys[i]) + 2] === 0
					 || counts[parseInt(keys[i]) + 1] == null || counts[parseInt(keys[i]) + 2] == null) {
						return false;
					}
					counts[keys[i]]--;
					counts[parseInt(keys[i]) + 1]--;
					counts[parseInt(keys[i]) + 2]--;
				}
				if (counts[keys[i]] !== 0 && counts[keys[i]] !== 3) {
					return false;
				}
				i++;
				if (counts[keys[i]] !== 0 && counts[keys[i]] !== 3) {
					return false;
				}
				return true;
			},
		}
	}
</script>

<style>
	image {
		width: 100%;
		height: 100%;
		background-size: cover; /* 图片充满容器 */
	}
	.footer1 {
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    margin-top: 15rpx; /* 上下留出一定的间距 */
	}	
	.btn-container {
	    display: flex;
	    justify-content: space-between;
	    align-items: center;
	    width: 100%;
	    margin: 0 auto;
	}   
	
	.can-win {
	    color: #fff;
	    background-color: #4caf50;
	    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
	}
	.not-win {
	    color: #fff;
	    background-color: #9e9e9e;
	    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		pointer-events: none;
	}
	
	.btn-container button {
	    width: 70px;
	    height: 40px;
	    font-size: 16px;
	    margin-bottom: 20rpx;
		
		box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
		border-radius: 5px;
		transition: transform 0.2s ease;
	}
	.cards {
	    display: flex;
	    flex-wrap: wrap;
	    justify-content: flex-start;
	    align-items: center;
	    width: 100%;
		padding-left: 10rpx;
	    box-sizing: border-box;
	}
	
	.card {
	    height: 120rpx;
	    width: 90rpx;
	    margin-bottom: 20rpx;
	    margin-right: 5rpx; /*添加水平方向间隔*/
	    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
	    border-radius: 5px;
	    transition: transform 0.2s ease;
		border: 4rpx solid transparent;

	}

	.is-clicked {
	    transform: scale(1.1);
	}
	.new-card {
	    border: 4rpx solid #ff0000;
	}
	.will-win {
		border: 4rpx solid #00ffff;
	}
	.ope-choosed {
		border: 4rpx solid #0000ff;
	}
	.can-gang {
		border-radius: 5px;
		background-color: #00ffff;
	}
</style>

